package com.ywjh.inter.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.ywjh.inter.entity.BGluRangeEntity;

public class BGluRangeDAO {

	public boolean insert(Connection conn, List<BGluRangeEntity> list) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn
				.prepareStatement("insert into bglu_range(plan_id,warning_range,user_id,status) values(?,?,?,?)");
		for (BGluRangeEntity bGluRangeEntity : list) {
			ps.setInt(1, bGluRangeEntity.getPlan_id());
			ps.setString(2, bGluRangeEntity.getWarning_range());
			ps.setInt(3, bGluRangeEntity.getUser_id());
			ps.setInt(4, bGluRangeEntity.getStatus());
			ps.addBatch();
		}
		if (ps.executeBatch().length > 0) {
			b = true;
		}
		return b;
	}

	public Map<Integer, BGluRangeEntity> findByUserId(Connection conn, int user_id) throws SQLException {
		Map<Integer, BGluRangeEntity> map = new LinkedHashMap<Integer, BGluRangeEntity>();
		PreparedStatement ps = conn.prepareStatement("select * from bglu_range where user_id=? and status=1");
		ps.setInt(1, user_id);
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			BGluRangeEntity bGluRangeEntity = fill(rs);
			Integer key = bGluRangeEntity.getPlan_id();
			map.put(key, bGluRangeEntity);
		}
		return map;
	}

	private BGluRangeEntity fill(ResultSet rs) throws SQLException {
		BGluRangeEntity ee = new BGluRangeEntity();
		ee.setId(rs.getInt("id"));
		ee.setPlan_id(rs.getInt("plan_id"));
		ee.setStatus(rs.getInt("status"));
		ee.setUser_id(rs.getInt("user_id"));
		ee.setWarning_range(rs.getString("warning_range"));
		return ee;
	}

	public boolean delete(Connection conn, int userId) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn.prepareStatement("delete from bglu_range where user_id=?");
		ps.setInt(1, userId);
		if (ps.executeUpdate() > 0) {
			b = true;
		}
		return b;
	}

}
